package com.jerry.usbserial.util.task.usb2

import android.content.Context
import com.jerry.usbserial.activity.UsbService
import com.jerry.usbserial.util.*

/**
 * Created by dugang on 2020/7/15.
 */
class USBMenuTask(context: Context, usbService: UsbService, waitSendData: WaitSendData) : BaseTask(context, usbService, waitSendData) {
    companion object {
        private const val STEP_UPDATE_MENU_TEST = 1
        private const val STEP_UPDATE_MENU = 2
        private const val STEP_UPDATE_MENU_FINISH = 3
    }

    override fun menuData(data: List<MenuItem>) {
        super.menuData(data)
        addCmd(SendItem(STEP_UPDATE_MENU_TEST, "AE5AA501000000E11E".hexToByteArray()))
        data.forEach {
            val cmdList = mutableListOf<Byte>()
            cmdList.addAll("0024A004".hexToByteArray().toList())
            val deviceId = java.lang.Long.toHexString("708901880000".toLong())
            cmdList.addAll(deviceId.hexToByteArray().toList())
            cmdList.addAll("01020302".hexToByteArray().toList())
            cmdList.add(it.id.toByte())
            cmdList.addAll("01".hexToByteArray().toList())
            cmdList.add(it.temputer.toByte())
            cmdList.addAll((it.time * 60).to2HByteArray().toList())
            val name = it.name.toByteArray(charset("GB2312"))
            cmdList.addAll(name.copyInto(20, 32).toList())

            val crcList = mutableListOf<Byte>()
            crcList.addAll("AEE11E".hexToByteArray().toList())
            crcList.addAll(cmdList)
            val crc = CRCUtil.getCrc16(crcList.toByteArray(), crcList.size).to2HByteArray()

            cmdList.addAll(crc.toList())
            cmdList.addAll("E11E".hexToByteArray().toList())

            val sendList = mutableListOf<Byte>()
            sendList.addAll("AE5AA5".hexToByteArray().toList())
            sendList.addAll(cmdList)

            addCmd(SendItem(STEP_UPDATE_MENU, sendList.toByteArray(), crc))
        }

        addCmd(SendItem(STEP_UPDATE_MENU_FINISH, "AE5AA503000000E11E".hexToByteArray()))
    }

    override fun checkResult(receive: ByteArray, lastSend: SendItem): Boolean {
        return when {
            lastSend.check == null -> true

            lastSend.step == STEP_UPDATE_MENU_TEST -> {

                true
            }

            lastSend.step == STEP_UPDATE_MENU -> {
                true
            }
            else -> true

        }
    }

    override fun printMessage(lastSend: SendItem): String? {

        return null
    }
}